package org.biogroovy.io;

import groovy.xml.MarkupBuilder

import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.text.SimpleDateFormat

import org.biogroovy.models.IModel

/**
 * This base class provides a simple extension point for writers.
 * 
 * @param <P> the model type
 */
public abstract class AbsWriter<P extends IModel> implements IWriter<P> {
	
	protected String defExtension;
	protected SimpleDateFormat dateFormatter = new SimpleDateFormat("YYYY-MM-dd");
	
	public AbsWriter(){
		
	}

	/**
	 * Constructor.
	 * @param defExtension the default file extension i.e. ".gene.xml"
	 */
	public AbsWriter(String defExtension) {
		this.defExtension = defExtension;
	}
	

	@Override
	public void writeCollectionSeparately(Collection<P> seqs, Path outputDir, boolean autoCreateDir) throws IOException {
		if(!outputDir.toFile().exists()){
			if (autoCreateDir){
				outputDir.toFile().mkdirs();
			}else {
				throw new IOException("The directory does not exist: " + outputDir);
			}
		}
		
		seqs.each {P seq ->
			String name = seq.modelId;
			
			Path path = Paths.get(outputDir.toAbsolutePath(), name);
			
			write(seq, Files.newOutputStream(path));
			
		}

	};

	/**
	 * Creates an XML node for the POJO using the builder.
	 */
	protected abstract void createXML(MarkupBuilder builder, P pojo);






}
